//
//  ViewController.swift
//  videoPlayer
//
//  Created by xwl on 2019/2/26.
//  Copyright © 2019年 xuwanliang. All rights reserved.
//


import Foundation
import CoreVideo
import AVFoundation
import UIKit

let DocumetnPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first


class ViewController: UIViewController, CameraCaptureDelegate, VideoPlayerDelegate {
    
    @IBOutlet weak var _switchBtn: UIButton!
    @IBOutlet weak var _imgview: UIImageView!
    
    lazy var m_camera: CameraOption! = nil
    var renderview: MetalView! = nil
    var myplayer: MyVideoPlayer! = nil
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        //UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation")
        print("0");
        //        guard let windowScene = view.window?.windowScene else { return }
        //        print("000");
        //        // Request the window scene to rotate to any landscape orientation.
        //        windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: .landscape)) { error in
        //            print("11111");
        //        }
        
        
        renderview = view as? MetalView
        print("2222");
        _switchBtn.setTitleColor(UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: UIControl.State.normal)
        _switchBtn.addTarget(self, action:#selector(switchBtnTapped), for:.touchUpInside)
        
        fourTimer()
        
        //let size = showScreenSize()
        //renderview.initInterleaveBuffer(width: Int(size.width), height: Int(size.height))
        //renderview.initInterleaveBuffer(width: 500, height: 500)
        
        self.m_camera = CameraOption(self)
        self.myplayer = MyVideoPlayer(self)
        
    }
    
    func videoBuffer(_ pixelBuffer: CVPixelBuffer!) {
        renderview.drawYUV(pixelBuffer)
    }
    
    func captureBuffer(_ sampleBuffer: CMSampleBuffer!) {
        if let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer){
            //let y_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0)
            //let y_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0)
            //print("output frame size: \(y_width)x\(y_height)")
            
            //CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.readOnly)
            //let image = CIImage(cvPixelBuffer: pixelBuffer)//.oriented(CGImagePropertyOrientation.right)
            //let capturedImage = UIImage(ciImage: image)
            
            renderview.drawYUV(pixelBuffer)
            
            //CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.readOnly)
            //DispatchQueue.main.async(execute: {
            //    self._imgview.image = capturedImage
            //})
        }
    }
    
    
    func setResolution(width: Int, height: Int) {
        
    }
    
    
    override func viewDidAppear(_ animated: Bool) {
        
    }
    
    
    
    @objc func switchBtnTapped(){
        print("tapped")
        //renderview.updateColor()
        //renderview.setNeedsDisplay()
        //self.m_camera.startRuning()
    }
    
    
    func fourTimer() -> Void {
        Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(timeRepeat(_:)), userInfo: nil, repeats: true)
    }
    @objc func timeRepeat(_ time:Timer) -> Void {
        //print("第四个定时器触发: \(String(format:"%.2f",Date().timeIntervalSince1970))")
        renderview.updateColor()
        //renderview.setNeedsDisplay()
    }
    func showScreenSize() -> CGSize{
        var drawableSize = UIScreen.main.bounds.size
        drawableSize.width *= UIScreen.main.nativeScale
        drawableSize.height *= UIScreen.main.nativeScale
        print("ScreenSize: \(drawableSize)")
        
        return drawableSize
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        //renderview.autoResizeDrawable = false
        //renderview.drawableSize = CGSize(width: 2868, height: 1320)
        //renderview.setNeedsDisplay()
    }
    
    //隐藏状态栏
    override var prefersStatusBarHidden:Bool{
        return true
    }
    //屏幕自动旋转
    override var shouldAutorotate:Bool{
        return true
    }
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
        return .landscapeRight
    }
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .landscapeRight
    }
}

